import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../constants/app_colors.dart';

class TranslationInput extends StatelessWidget {
  final TextEditingController controller;
  final VoidCallback onClear;
  final VoidCallback onListening;
  final bool isListening;
  final bool isTranslating;
  final String? translatedText;
  final bool showTranslationOnly;
  final VoidCallback? onPlayTranslation;
  final VoidCallback? onCopyText;

  const TranslationInput({
    Key? key,
    required this.controller,
    required this.onClear,
    required this.onListening,
    this.isListening = false,
    this.isTranslating = false,
    this.translatedText,
    this.showTranslationOnly = false,
    this.onPlayTranslation,
    this.onCopyText,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 检查是否有可播放和复制的内容
    final bool hasOriginalText = controller.text.isNotEmpty;
    final bool hasTranslatedText = translatedText != null && translatedText!.isNotEmpty;
    final bool hasAnyContent = hasOriginalText || hasTranslatedText;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.06),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.02),
            blurRadius: 2,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 输入框：当showTranslationOnly为true且有译文时不显示
          if (!showTranslationOnly || !hasTranslatedText)
            Container(
              constraints: const BoxConstraints(minHeight: 48),
              child: TextField(
                controller: controller,
                decoration: const InputDecoration(
                  hintText: '输入文字或点击麦克风说话...',
                  hintStyle: TextStyle(
                    color: AppColors.textSecondary,
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 8),
                ),
                style: const TextStyle(
                  color: AppColors.textPrimary,
                  fontSize: 15,
                  fontWeight: FontWeight.w500,
                  height: 1.4,
                ),
                maxLines: 4,
                minLines: 1,
              ),
            ),

          // 分割线（当有原文和译文时显示）
          if (hasOriginalText && hasTranslatedText && !showTranslationOnly) ...[
            const SizedBox(height: 12),
            Container(
              height: 1,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    AppColors.primary.withValues(alpha: 0.1),
                    AppColors.primary.withValues(alpha: 0.3),
                    AppColors.primary.withValues(alpha: 0.1),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 12),
          ],

          // 显示译文（如果有）
          if (hasTranslatedText) ...[
            if (!showTranslationOnly || !hasOriginalText) const SizedBox(height: 8),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(vertical: 8),
              child: Text(
                translatedText!,
                style: const TextStyle(
                  color: AppColors.primary,
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                  height: 1.5,
                ),
              ),
            ),
          ],

          // 底部按钮区域
          const SizedBox(height: 16),
          Row(
            children: [
              // 播放按钮 - 有译文时才可用
              _buildActionButton(
                icon: Icons.volume_up_outlined,
                isEnabled: hasTranslatedText,
                onPressed: hasTranslatedText ? onPlayTranslation : null,
                tooltip: '播放译文',
              ),
              const SizedBox(width: 12),
              // 复制按钮 - 有内容时才可用
              _buildActionButton(
                icon: Icons.copy_outlined,
                isEnabled: hasAnyContent,
                onPressed: hasAnyContent ? () => _copyContent(hasOriginalText, hasTranslatedText) : null,
                tooltip: _getCopyTooltip(hasOriginalText, hasTranslatedText),
              ),
              const SizedBox(width: 12),
              // 清空按钮 - 有内容时才可用，修改为调用_handleClear
              _buildActionButton(
                icon: Icons.clear_outlined,
                isEnabled: hasAnyContent,
                onPressed: hasAnyContent ? _handleClear : null,
                tooltip: '清空所有内容',
              ),
              const Spacer(),
              // 麦克风按钮
              GestureDetector(
                onTap: onListening,
                child: Container(
                  width: 52,
                  height: 52,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: isListening
                          ? [const Color(0xFFE53E3E), const Color(0xFFFC8181)]
                          : [AppColors.primary, AppColors.primary.withValues(alpha: 0.8)],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    ),
                    borderRadius: BorderRadius.circular(26),
                    boxShadow: [
                      BoxShadow(
                        color: (isListening ? const Color(0xFFE53E3E) : AppColors.primary)
                            .withValues(alpha: 0.4),
                        blurRadius: isListening ? 16 : 12,
                        spreadRadius: isListening ? 2 : 0,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Icon(
                        isListening ? Icons.stop_rounded : Icons.mic_rounded,
                        color: Colors.white,
                        size: 24,
                      ),
                      if (isListening)
                        // 添加波纹动画效果
                        Positioned.fill(
                          child: LayoutBuilder(
                            builder: (context, constraints) {
                              return CustomPaint(
                                painter: RecordingPulsePainter(
                                  color: Colors.white.withValues(alpha: 0.6),
                                ),
                                size: Size(constraints.maxWidth, constraints.maxHeight),
                              );
                            },
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required bool isEnabled,
    required VoidCallback? onPressed,
    required String tooltip,
  }) {
    return Tooltip(
      message: tooltip,
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onPressed,
          borderRadius: BorderRadius.circular(20),
          child: Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: isEnabled
                  ? AppColors.primary.withValues(alpha: 0.1)
                  : Colors.grey.withValues(alpha: 0.05),
              borderRadius: BorderRadius.circular(20),
              border: Border.all(
                color: isEnabled
                    ? AppColors.primary.withValues(alpha: 0.2)
                    : Colors.grey.withValues(alpha: 0.1),
                width: 1,
              ),
            ),
            child: Icon(
              icon,
              color: isEnabled
                  ? AppColors.primary
                  : Colors.grey.withValues(alpha: 0.4),
              size: 20,
            ),
          ),
        ),
      ),
    );
  }

  String _getCopyTooltip(bool hasOriginalText, bool hasTranslatedText) {
    if (hasOriginalText && hasTranslatedText) {
      return '复制原文和译文';
    } else if (hasTranslatedText) {
      return '复制译文';
    } else if (hasOriginalText) {
      return '复制原文';
    } else {
      return '复制内容';
    }
  }

  Future<void> _copyContent(bool hasOriginalText, bool hasTranslatedText) async {
    String contentToCopy = '';

    if (hasOriginalText && hasTranslatedText) {
      // 有原文和译文，都复制
      contentToCopy = '${controller.text}\n\n${translatedText!}';
    } else if (hasTranslatedText) {
      // 只有译文，复制译文
      contentToCopy = translatedText!;
    } else if (hasOriginalText) {
      // 只有原文，复制原文
      contentToCopy = controller.text;
    }

    if (contentToCopy.isNotEmpty) {
      await Clipboard.setData(ClipboardData(text: contentToCopy));
      // 可以在这里添加一个简单的提示，告诉用户复制成功
    }
  }

  Future<void> _handleClear() async {
    // 清空输入框
    controller.clear();
    // 调用父组件的清空回调，用于清空译文和其他状态
    onClear();
  }
}

// 录音波纹动画绘制器
class RecordingPulsePainter extends CustomPainter {
  final Color color;
  final Paint _paint;

  RecordingPulsePainter({required this.color}) : _paint = Paint()..color = color..style = PaintingStyle.stroke..strokeWidth = 1.5;

  @override
  void paint(Canvas canvas, Size size) {
    final double now = DateTime.now().millisecondsSinceEpoch % 2000 / 2000;
    final double maxRadius = size.width / 2 - 4;

    // 绘制三个大小不同的圆形波纹
    for (int i = 0; i < 3; i++) {
      final double phase = (now + i / 3) % 1.0;
      final double radius = maxRadius * phase;

      // 随着半径增大，透明度降低
      _paint.color = color.withValues(alpha: (1.0 - phase) * 0.8);

      canvas.drawCircle(
        Offset(size.width / 2, size.height / 2),
        radius,
        _paint,
      );
    }
  }

  @override
  bool shouldRepaint(RecordingPulsePainter oldDelegate) => true;
}